'''
【**重要**】，函数
'''
from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01.models import Department, UserInfo


# Create your views here.

def index(request):
    return HttpResponse("欢迎使用")

def user_list(request):
    return render(request,'user_list.html')

def user_add(request):
    return HttpResponse("添加用户")

def sth(request):
    print(request.method)
    #在url上传递值，age=1&name=11
    print(request.GET)
    #在请求体重提交数据
    print(request.POST)
    return HttpResponse("sth")

def login(request):
    if request.method=="GET":
        return render(request,"login.html")
    print(request.POST)
    username = request.POST.get("user")
    password = request.POST.get("pwd")
    if username=="root" and password=="123":
        return redirect("http://www.baidu.com")
    return render(request,'login.html',{"error_msg":"用户名或密码错误"})

def orm(request):
    # Department.objects.create(title="技术部")
    # Department.objects.create(title="销售部")
    # Department.objects.create(title="IT部")
    # Department.objects.create(title="运营部")
    # UserInfo.objects.create(name="武沛齐", password="123", age=19)
    # UserInfo.objects.create(name="朱虎飞", password="666", age=29)
    # UserInfo.objects.create(name="吴阳军", password="666")
    # Department.objects.filter(title='技术部').delete()
    #获取数据
    data_list = UserInfo.objects.all()
    for item in data_list:
        print(f"{item.name}")

    firstone= UserInfo.objects.first()
    print(firstone.id,firstone.name)

    #更新数据
    UserInfo.objects.filter(id=2).update(age=999)

    return HttpResponse("OK")


#####用户#######
def info_list(request):
    data_list = UserInfo.objects.all()
    return render(request,"info_list.html",{"data_list":data_list})

def info_add(request):
    if request.method=="GET":
        return render(request,"info_add.html")
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    UserInfo.objects.create(name=user,password=pwd,age=age)
    return redirect("/info/list")

def info_delete(request):
    nid = request.GET.get('nid')
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/info/list")